package com.wtwd.device.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author zdl
 * @Description
 * @create 2020-07-20 14:47
 */
@Configuration
public class CacheConfig {
    private static final int DEFAULT_TTL = 60;
    private static final int DEFAULT_MAXSIZE = 100;


    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 配置缓存管理器
     *
     * @return
     */
    @Bean("caffeineManager")
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterAccess(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100));
        // 缓存的最大条数
        //.maximumSize(1000));
        return cacheManager;
    }

    @Primary
    @Bean("localCacheManager")
    public CacheManager createCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caches = new ArrayList<>();
        for (CacheEum c : CacheEum.values()) {
            caches.add(new CaffeineCache(c.name(),
                    Caffeine.newBuilder()
                            .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                            .build())
            );
        }
        cacheManager.setCaches(caches);
        return cacheManager;
    }

    public enum CacheEum {
        USER(120),
        AUTHCODE(600),
        WEATHER_BLACKLIST(600)
        ;
        //过期时间（秒）
        private int ttl = DEFAULT_TTL;
        //过期时间（秒）
        private int maxSize = DEFAULT_TTL;

        CacheEum(int ttl) {
            this.ttl = ttl;
        }

        CacheEum(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        public int getTtl() {
            return ttl;
        }

        public int getMaxSize() {
            return maxSize;
        }
    }
}
